package net.ojbk.study.curriculumDesign.web.handlers.impl.sall;

import net.ojbk.study.curriculumDesign.beans.APIResult;
import net.ojbk.study.curriculumDesign.beans.sall.Sall;
import net.ojbk.study.curriculumDesign.beans.canvasmodel.Canvas;
import net.ojbk.study.curriculumDesign.beans.usermanage.User;
import net.ojbk.study.curriculumDesign.common.api.APICodeConstant;
import net.ojbk.study.curriculumDesign.service.sall.ISallService;
import net.ojbk.study.curriculumDesign.service.canvasmodel.ICanvasService;
import net.ojbk.study.curriculumDesign.web.handlers.sallmodel.ISallController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("sall")
public class SallControllerImpl implements ISallController {
    @Autowired
    @Qualifier("sallService")
    private ISallService sallService;
    @Autowired
    @Qualifier("canvasService")
    private ICanvasService iCanvasService;
    @Autowired
    private ServletContext servletContext;
    private RequestAttributes requestAttributes;
    @Autowired
    private HttpSession session;


    @RequestMapping("index")
    public Object index(){
        User user=(User)session.getAttribute("user");
        //得到User 对象
        //登录状态
        if(user==null){
            return "redirect:../user/login";
        }//转跳登录页面
        else {
            System.out.println(user.getUid());
            Set<Canvas> canvasSet=new HashSet<>();
            canvasSet=iCanvasService.selectAllInsallCanvas(user.getUid());
            session.setAttribute("myCanvas",canvasSet);//sessionScope
        }
        return "setSall";//转跳到设置拍卖页面
    }

    @RequestMapping("salls")
    public String salls(){
        return "showallsall";
    }

    /**
     *设置拍卖
     *拍卖油画->拍卖者
     *@param sall
     * @return success message;
     * */
    @Override
    @RequestMapping(value = "setsall",method = RequestMethod.POST)
    @ResponseBody
    //根据session   uid 识别该用户的油画cid
    public Object setSall(@RequestBody Sall sall) {
        User user=(User)session.getAttribute("user");
        //得到User 对象
        if (user==null) servletContext.getRequestDispatcher("login");
        if (sall.getEndtime().getTime()<(new Date().getTime())||sall.getCid()==0){
            return APIResult.createError(new APICodeConstant()
            ,"时间错误");
        }
        System.out.println(user.getUid());//test
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//testdataformat
        System.out.println(format.format(sall.getEndtime()));//test
        sall.setUid(user.getUid());//初始uid为拍卖者的uid
        //油画id为cid的 记录行数
        int count=sallService.getCount(sall);
        //设置sall.count=count+1;
        sall.setCount(count+1);
        System.out.println(sall.getMaxprice());
        List<Sall> list=(List<Sall>)servletContext.getAttribute("salls");//applicationScope
        Canvas canvas=iCanvasService.getOneByid(sall.getCid());
        System.out.println(canvas.getName());
        Set<Canvas> canvasSet=(Set<Canvas>)servletContext.getAttribute("canvasOnSall");//applicationScope
        Set<Canvas> ssSet=new HashSet<>();//sessionScope
        ssSet=(Set<Canvas>)session.getAttribute("myCanvas");
        ssSet.remove(canvas);//从session移除拍卖的油画，避免下次重选
        canvasSet.add(canvas);
        list.add(sall);
        sallService.addOneSall(sall);
        return APIResult.createSuccessMessage(new APICodeConstant(),"拍卖成功");
    }

    /**2019/1/9 发现bug还没修改
     * 拍卖时间到，成交
     * 执行successSall(Sall sall);
     * @param sall
     * */
    @Deprecated
    @Override
    @RequestMapping(value = "offsall",method = RequestMethod.POST)
    @ResponseBody
    public void offSall(@RequestBody Sall sall){
        if(sall!=null&&sall.getEndtime().getTime()< (new Date().getTime())) {
            sallService.successSall(sall);
        }else {

        }
    }

    /**
     * 参与竞拍,如果价格高于最后一次拍卖价，更新拍卖信息，
     * 只更新maxprice和uid
     * */
    @Override
    @RequestMapping(value = "joinsall",method = RequestMethod.POST)
    @ResponseBody
    public Object joinSall(@RequestBody Sall sall){
        User user=new User();
        user=(User)session.getAttribute("user");
        if (user==null) return APIResult.createFail(new APICodeConstant(),"请先登录");
        else{
//        这里需要取session 的uid,暂时测试用自己输入的uid
        Sall s=(Sall)servletContext.getAttribute("sall");
        if (s.getMaxprice()>sall.getMaxprice())return APIResult.createFail(new APICodeConstant(),
                "报价低于拍卖价，请重新输入报价");
        else {
            sall.setUid(((User) session.getAttribute("user")).getUid());
            sall.setCid(s.getCid());
            sall.setCount(s.getCount());
            sall.setEndtime(s.getEndtime());
            sall.setStatus(s.getStatus());
            List<Sall> sallList = (List<Sall>) servletContext.getAttribute("salls");
            sallList.remove(s);//old
            sallList.add(sall);//newb
            Canvas canvas = (Canvas) servletContext.getAttribute("canvas");
            canvas.setPrice(sall.getMaxprice());
            canvas.setUid(sall.getUid());
            sallService.updateOneSall(sall);
            iCanvasService.updateCanvas(canvas);
            System.out.println("updatedo");//test
            return APIResult.createSuccessMessage(new APICodeConstant(), "竞拍成功,竞拍仍在继续");
        }
        }
    }

    /**
     * 展示竞拍信息
     * @param cid
     * @return
     */
    @RequestMapping(value = "salldetail",method = RequestMethod.GET)
    public Object salldetail(@RequestParam("cid") int cid){
        //从上下文数据
        List<Sall> sallList =  (List<Sall>)servletContext.getAttribute("salls");
        Set<Canvas> canvasSet=(Set<Canvas>)servletContext.getAttribute("canvasOnSall");
         Sall sall=null;
         Canvas canvas=null;
        for (Sall s:sallList
             ) {
                if (s.getCid()==cid)
                {
                    sall=s;
                }
        }
        if (sall==null)return null;
        servletContext.setAttribute("sall",sall);
        for (Canvas c:canvasSet
             ) {
            if(c.getCid()==cid) {
                canvas = c;
            }
        }
        servletContext.setAttribute("canvas",canvas);
        return "salldetail";
    }
}
